class UserModel {
  final int id;
  final String username;
  final String? nickname;
  final String? avatar;
  final String? email;
  final String? phone;
  final String? openId; // open_id 用于消息发送
  final int? snowflakeId; // snowflake_id 用于 MQTT
  final DateTime? createdAt;

  UserModel({
    required this.id,
    required this.username,
    this.nickname,
    this.avatar,
    this.email,
    this.phone,
    this.openId,
    this.snowflakeId,
    this.createdAt,
  });

  factory UserModel.fromJson(Map<String, dynamic> json) {
    // 支持多种字段名：user_name (后端返回) 或 username
    String username = '';
    if (json['user_name'] != null && json['user_name'].toString().isNotEmpty) {
      username = json['user_name'].toString();
    } else if (json['username'] != null && json['username'].toString().isNotEmpty) {
      username = json['username'].toString();
    } else if (json['name'] != null && json['name'].toString().isNotEmpty) {
      username = json['name'].toString();
    }
    
    // 处理 id 字段：可能是 user_id (字符串) 或 id (数字)
    int userId = 0;
    if (json['user_id'] != null) {
      final userIdStr = json['user_id'].toString();
      userId = int.tryParse(userIdStr) ?? 0;
    } else if (json['id'] != null) {
      userId = json['id'] is int ? json['id'] : int.tryParse(json['id'].toString()) ?? 0;
    }
    
    // 处理 phone 字段：可能是 phone 或 mobile
    String? phone;
    if (json['phone'] != null && json['phone'].toString().isNotEmpty) {
      phone = json['phone'].toString();
    } else if (json['mobile'] != null && json['mobile'].toString().isNotEmpty) {
      phone = json['mobile'].toString();
    }
    
    // 处理 createdAt 字段：可能是 created_at (ISO 字符串) 或 create_time (时间戳)
    DateTime? createdAt;
    if (json['created_at'] != null) {
      try {
        createdAt = DateTime.parse(json['created_at'].toString());
      } catch (e) {
        // 解析失败，忽略
      }
    } else if (json['create_time'] != null) {
      try {
        final timestamp = json['create_time'] is int 
            ? json['create_time'] as int
            : int.tryParse(json['create_time'].toString());
        if (timestamp != null) {
          createdAt = DateTime.fromMillisecondsSinceEpoch(timestamp);
        }
      } catch (e) {
        // 解析失败，忽略
      }
    }
    
    // 处理 open_id 和 snowflake_id
    String? openId;
    if (json['open_id'] != null) {
      openId = json['open_id'].toString();
    }
    
    int? snowflakeId;
    if (json['snowflake_id'] != null) {
      snowflakeId = json['snowflake_id'] is int 
          ? json['snowflake_id'] as int
          : int.tryParse(json['snowflake_id'].toString());
    }
    
    // 处理 nickname：可能是 nickname 或 name
    String? nickname;
    if (json['nickname'] != null && json['nickname'].toString().isNotEmpty) {
      nickname = json['nickname'].toString();
    } else if (json['name'] != null && json['name'].toString().isNotEmpty) {
      nickname = json['name'].toString();
    }
    
    return UserModel(
      id: userId,
      username: username,
      nickname: nickname,
      avatar: json['avatar'],
      email: json['email'],
      phone: phone,
      openId: openId,
      snowflakeId: snowflakeId,
      createdAt: createdAt,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'username': username,
      'nickname': nickname,
      'avatar': avatar,
      'email': email,
      'phone': phone,
      'open_id': openId,
      'snowflake_id': snowflakeId,
      'created_at': createdAt?.toIso8601String(),
    };
  }
  
  /// 获取用于消息发送的 ID（优先使用 open_id，否则使用 username）
  String get messageId => openId ?? username;
}

